/*
 * Copyright 2011 Daniel Krieg
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.csf;

public abstract class ServiceProxy {
    private final ServiceTemplate serviceTemplate;

    public static Throwable translateException(ServiceProxy proxy, Class type, Throwable exception) {
        return proxy.translateException(type, exception);
    }

    public ServiceProxy(ServiceTemplate serviceTemplate) {
        this.serviceTemplate = serviceTemplate;
    }

    protected final ServiceTemplate getServiceTemplate() {
        return serviceTemplate;
    }

    protected Object execute(ServiceAdapter serviceAdapter) throws Throwable {
        return getServiceTemplate().execute(serviceAdapter);
    }

    protected Throwable translateException(Class type, Throwable exception) {
        assert type != null && exception != null;
        if(type.isAssignableFrom(exception.getClass())) {
            return exception;
        }

        Throwable throwable;
        try {
            if (exception instanceof ServiceException) {
                Throwable cause = exception.getCause();
                if (cause == null) {
                    throwable = (Throwable) type.getConstructor(new Class[]{String.class}).newInstance(new Object[]{exception.getMessage()});
                } else if (type.isAssignableFrom(cause.getClass())) {
                    return cause;
                } else {
                    try {
                        throwable = (Throwable) type.getConstructor(new Class[]{Throwable.class}).newInstance(new Object[]{exception});
                    } catch (NoSuchMethodException e) {
                        throwable = (Throwable) type.getConstructor(new Class[]{String.class}).newInstance(new Object[]{exception.getMessage()});
                    }
                }
            } else {
                try {
                    throwable = (Throwable) type.getConstructor(new Class[]{Throwable.class}).newInstance(new Object[]{exception});
                } catch (NoSuchMethodException e) {
                    throwable = (Throwable) type.getConstructor(new Class[]{String.class}).newInstance(new Object[]{exception.getMessage()});
                }
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return throwable;
    }
}
